import time

from flask import Flask, Response
from flask import render_template

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')
# 1-定义主页路由
@app.route('/index_standard')
def index_standard():
    return render_template('index_01_standard.html')

# 2-定义主页路由
@app.route('/index_custom')
def index_custom():
    return render_template('index_02_custom.html')

# 定义 SSE 事件流
@app.route('/sse')
def sse_stream():
    def event_stream():
        for i in range(20):
            yield f"data: 测试数据20-Message {i}\n\n"
            time.sleep(1)

    return Response(event_stream(),
                    content_type='text/event-stream')


# 自定义 SSE 事件流
@app.route('/sse_custom')
def sse_stream_custom():
    def event_stream():
        for i in range(20):
            # 1-自定义-事件ID
            event_id = str(i)
            # 2-自定义-事件类型
            event_type = "even" if i % 2 == 0 else "odd"
            # 3-自定义-事件数据
            data = f"Count: Message {i}"
            # 4-自定义-构造Server-Sent Event消息
            event = f"id: {event_id}\nevent: {event_type}\ndata: {data}\n\n"
            yield event
            time.sleep(1)

    return Response(event_stream(),
                    content_type='text/event-stream')
# 启动并指定端口
if __name__ == '__main__':
    app.run(port=8080, debug=True)
